#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "coursecard.h"
#include "changepassworddialog.h"
#include "feedbackdialog.h"
#include "customcalendarwidget.h"
#include <QSpacerItem>
#include <QLabel>
#include <QGridLayout>
#include <QScrollArea>
#include <QMessageBox>
#include <QTextBrowser>
#include <QDesktopServices>
#include <QDebug>
#include <QDir>
#include "common/common.h"
#include <QHeaderView>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QHttpMultiPart>
#include "MainWindow/coursecard_.h"
#include "UserLogin/cuserlogin.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initUI();
    setupPageTitles();
    connect(ui->stackedWidget, &QStackedWidget::currentChanged, this, &MainWindow::onPageChanged);

    // 连接设置页面标签的点击事件
    setupSettingPage();

    mNet_ = new QNetworkAccessManager(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setupPageTitles()
{
    // 设置初始页面标题
    int index = ui->stackedWidget->currentIndex();
    qDebug() << "curpage index: " << index;
    onPageChanged(ui->stackedWidget->currentIndex());
}

void MainWindow::onToolButtonClicked()
{
    QToolButton* pButton = qobject_cast<QToolButton*>(sender());
    if (pButton)
    {
        QString objectName = pButton->objectName();

        // 根据点击的按钮切换到对应页面
        if (objectName == "Schedule") {
            ui->stackedWidget->setCurrentIndex(0);
            //loadCourseCards();
            getCourseList();

        } else if (objectName == "Course") {
            ui->stackedWidget->setCurrentIndex(1);
        } else if (objectName == "CourseRecorder") {
            ui->stackedWidget->setCurrentIndex(2);
        } else if (objectName == "Student") {
            ui->stackedWidget->setCurrentIndex(3);
        } else if (objectName == "Ppt") {
            ui->stackedWidget->setCurrentIndex(4);
        } else if (objectName == "BlackBoard") {
            ui->stackedWidget->setCurrentIndex(5);
        } else if (objectName == "Setting") {
            ui->stackedWidget->setCurrentIndex(6);
        }
    }
}

void MainWindow::onPageChanged(int index)
{
    // 根据页面索引设置不同的标题文字
    switch (index) {
    case 0:
        m_pTitleLabel->setText("我的课表");
        // 切换到课表页面时加载课程数据
        if (index == 0 && !m_courseLoaded) {   // 课程页 && 未加载
            //loadCourseCards();
            getCourseList();
            m_courseLoaded = true;             // 只加载一次
        }
        break;
    case 1:
        m_pTitleLabel->setText("我的课程");
        break;
    case 2:
        m_pTitleLabel->setText("课程记录");
        break;
    case 3:
        m_pTitleLabel->setText(m_IsTeacher ? QString::fromUtf8("我的学生")
                                           : QString::fromUtf8("设备检测"));
        break;
    case 4:
        m_pTitleLabel->setText("我的课件");
        break;
    case 5:
        m_pTitleLabel->setText("黑板");
        break;
    case 6:
        m_pTitleLabel->setText("设置");
        break;
    default:
        m_pTitleLabel->setText("欢迎使用VVClass!");
        break;
    }
}

void MainWindow::initData()
{
    m_IsTeacher     =       true;
}

void MainWindow::setupCoursePage()
{
    // 定义每部分显示的课程卡片数量
    const int coursesPerSection = 8;

    // 创建一个主布局用于放置今日课程和昨日课程
    QVBoxLayout* mainLayout = new QVBoxLayout(ui->page_Course);
    mainLayout->setContentsMargins(10, 10, 10, 10);

    // 创建今日课程部分
    QLabel* todayLabel = new QLabel(tr("今日课程 (%1 节)").arg(coursesPerSection), this);
    todayLabel->setFont(QFont("Arial", 14, QFont::Bold));
    todayLabel->setStyleSheet("QLabel { color : blue; }");
    mainLayout->addWidget(todayLabel);

    // 创建今日课程网格布局
    QWidget* todayWidget = new QWidget();
    QGridLayout* todayGridLayout = new QGridLayout(todayWidget);
    todayGridLayout->setAlignment(Qt::AlignTop);

    // 创建今日课程卡片
    for (int i = 0; i < coursesPerSection; ++i) {
        CourseCard* card = new CourseCard(this);
        // 计算行和列的位置 (每行最多4个卡片)
        int row = i / 4;
        int col = i % 4;
        todayGridLayout->addWidget(card, row, col);
        m_List_CourseCards.append(card);
    }

    mainLayout->addWidget(todayWidget);

    // 创建昨日课程部分
    QLabel* yesterdayLabel = new QLabel(tr("昨日课程 (%1 节)").arg(coursesPerSection), this);
    yesterdayLabel->setFont(QFont("Arial", 14, QFont::Bold));
    yesterdayLabel->setStyleSheet("QLabel { color : blue; }");
    mainLayout->addWidget(yesterdayLabel);

    // 创建昨日课程网格布局
    QWidget* yesterdayWidget = new QWidget();
    QGridLayout* yesterdayGridLayout = new QGridLayout(yesterdayWidget);
    yesterdayGridLayout->setAlignment(Qt::AlignTop);

    // 创建昨日课程卡片
    for (int i = 0; i < coursesPerSection; ++i) {
        CourseCard* card = new CourseCard(this);
        // 计算行和列的位置 (每行最多4个卡片)
        int row = i / 4;
        int col = i % 4;
        yesterdayGridLayout->addWidget(card, row, col);
        m_List_CourseCards.append(card);
    }

    mainLayout->addWidget(yesterdayWidget);
}

void MainWindow::initUI()
{
    // 窗口标题
    setWindowTitle("VVClass");

    // 创建用于显示页面标题的标签
    m_pTitleLabel = new QLabel(this);
    m_pTitleLabel->setFont(QFont("Arial", 16, QFont::Bold));
    m_pTitleLabel->setStyleSheet("QLabel { color : blue; }");

    // 将标题标签添加到布局中
    ui->horizontalLayout->insertWidget(0, m_pTitleLabel);

    // 设置课程页面
    setupCoursePage();

    // 设置课表页面
    // setupSchedulePage();

    QToolButton* pToolButton_Company  = new QToolButton(this);
    pToolButton_Company->setIcon(QIcon(":/res/company.png"));
    pToolButton_Company->setText("        ");
    pToolButton_Company->setObjectName("Company");
    connect(pToolButton_Company, &QToolButton::clicked, this, &MainWindow::onToolButtonClicked);
    m_List_ToolgButton.append(pToolButton_Company);

    QToolButton* pToolButton_User_Photo  = new QToolButton(this);
    pToolButton_User_Photo->setIcon(QIcon(":/res/teacher.png"));
    pToolButton_User_Photo->setText("        ");
    pToolButton_User_Photo->setObjectName("UserPhoto");
    connect(pToolButton_User_Photo, &QToolButton::clicked, this, &MainWindow::onToolButtonClicked);
    m_List_ToolgButton.append(pToolButton_User_Photo);


    QToolButton* pToolButton_Schedule  = new QToolButton(this);
    pToolButton_Schedule->setIcon(QIcon(":/res/teacher.png"));
    pToolButton_Schedule->setText("我的课表");
    pToolButton_Schedule->setObjectName("Schedule");
    connect(pToolButton_Schedule, &QToolButton::clicked, this, &MainWindow::onToolButtonClicked);
    m_List_ToolgButton.append(pToolButton_Schedule);

    QToolButton* pToolButton_Course  = new QToolButton(this);
    pToolButton_Course->setIcon(QIcon(":/res/teacher.png"));
    pToolButton_Course->setText("我的课程");
    pToolButton_Course->setObjectName("Course");
    connect(pToolButton_Course, &QToolButton::clicked, this, &MainWindow::onToolButtonClicked);
    m_List_ToolgButton.append(pToolButton_Course);

    QToolButton* pToolButton_Course_Recorder  = new QToolButton(this);
    pToolButton_Course_Recorder->setIcon(QIcon(":/res/teacher.png"));
    pToolButton_Course_Recorder->setText("课程记录");
    pToolButton_Course_Recorder->setObjectName("CourseRecorder");
    connect(pToolButton_Course_Recorder, &QToolButton::clicked, this, &MainWindow::onToolButtonClicked);
    m_List_ToolgButton.append(pToolButton_Course_Recorder);





//    QAction *action_Company = new QAction(QIcon(":/res/company.png"), "", this);
//    ui->toolBar->addAction(action_Company);

//    QAction *action_User_Photo = new QAction(QIcon(":/res/teacher.png"), "", this);
//    ui->toolBar->addAction(action_User_Photo);


//    QAction *action_Schedule = new QAction(QIcon(":/res/teacher.png"), "我的课表", this);
//    ui->toolBar->addAction(action_Schedule);


//    QAction *action_Course = new QAction(QIcon(":/res/teacher.png"), "我的课程", this);
//    ui->toolBar->addAction(action_Course);

//    QAction *action_Course_Recorder = new QAction(QIcon(":/res/teacher.png"), "课程记录", this);
//    ui->toolBar->addAction(action_Course_Recorder);

    if(m_IsTeacher)
    {
        QToolButton* pToolButton_Student  = new QToolButton(this);
        pToolButton_Student->setIcon(QIcon(":/res/teacher.png"));
        pToolButton_Student->setText("我的学生");
        pToolButton_Student->setObjectName("Student");
        connect(pToolButton_Student, &QToolButton::clicked, this, &MainWindow::onToolButtonClicked);
        m_List_ToolgButton.append(pToolButton_Student);

        QToolButton* pToolButton_Ppt  = new QToolButton(this);
        pToolButton_Ppt->setIcon(QIcon(":/res/teacher.png"));
        pToolButton_Ppt->setText("我的课件");
        pToolButton_Ppt->setObjectName("Ppt");
        connect(pToolButton_Ppt, &QToolButton::clicked, this, &MainWindow::onToolButtonClicked);
        m_List_ToolgButton.append(pToolButton_Ppt);

        QToolButton* pToolButton_BlackBoard  = new QToolButton(this);
        pToolButton_BlackBoard->setIcon(QIcon(":/res/teacher.png"));
        pToolButton_BlackBoard->setText("  黑板  ");
        pToolButton_BlackBoard->setObjectName("BlackBoard");
        connect(pToolButton_BlackBoard, &QToolButton::clicked, this, &MainWindow::onToolButtonClicked);
        m_List_ToolgButton.append(pToolButton_BlackBoard);

        QToolButton* pToolButton_Setting  = new QToolButton(this);
        pToolButton_Setting->setIcon(QIcon(":/res/teacher.png"));
        pToolButton_Setting->setText("  设置  ");
        pToolButton_Setting->setObjectName("Setting");
        connect(pToolButton_Setting, &QToolButton::clicked, this, &MainWindow::onToolButtonClicked);
        m_List_ToolgButton.append(pToolButton_Setting);

    }
    else
    {
//        QToolButton* pToolButton_Dev  = new QToolButton(this);
//        pToolButton_Dev->setIcon(QIcon(":/res/teacher.png"));
//        pToolButton_Dev->setText("设备检测");
//        m_List_ToolgButton.append(pToolButton_Dev);

//        QToolButton* pToolButton_op  = new QToolButton(this);
//        pToolButton_op->setIcon(QIcon(":/res/teacher.png"));
//        pToolButton_op->setText("操作手册");
//        m_List_ToolgButton.append(pToolButton_op);

//        QToolButton* pToolButton_Setting  = new QToolButton(this);
//        pToolButton_Setting->setIcon(QIcon(":/res/teacher.png"));
//        pToolButton_Setting->setText("帮助");
//        m_List_ToolgButton.append(pToolButton_Setting);

    }

    for(auto it:m_List_ToolgButton)
    {
        it->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        it->setStyleSheet("QToolButton { color: white; spacing: 20px;}");
        //it->setStyleSheet("QToolButton:checked { background-color: gray; }");
        ui->toolBar->addWidget(it);
    }


    // 设置工具栏的样式表，改变背景颜色为蓝色
    ui->toolBar->setStyleSheet("QToolBar { background-color: rgb(76,128,240);spacing: 10px;}");
    ui->toolBar->setIconSize(QSize(48,48));
    this->showMaximized();

}

void MainWindow::setupSettingPage()
{

    // 连接设置页面标签的点击事件
    connect(ui->label_uploadAvatar, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);
    connect(ui->label_username, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);
    connect(ui->label_phone, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);
    connect(ui->label_modifyPassword, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);
    connect(ui->label_feedback, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);
    connect(ui->label_userAgreement, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);
    connect(ui->label_childAgreement, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);
    connect(ui->label_privacyPolicy, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);
    // > 事件
    connect(ui->label_arrow, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);
    connect(ui->label_arrow_2, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);
    connect(ui->label_arrow_3, &ClickableLabel::clicked, this, &MainWindow::onSettingLabelClicked);

    // 连接退出登录按钮的点击事件
    connect(ui->pushButton_logout, &QPushButton::clicked, this, &MainWindow::onLogoutButtonClicked);
}

void MainWindow::onSettingLabelClicked()
{
    ClickableLabel* label = qobject_cast<ClickableLabel*>(sender());
    if (label) {
        QString objectName = label->objectName();

        if (objectName == "label_uploadAvatar") {
            QMessageBox::information(this, "提示", "上传头像功能正在开发中...");
        } else if (objectName == "label_username") {
            QMessageBox::information(this, "提示", "用户信息功能正在开发中...");
        } else if (objectName == "label_phone") {
            QMessageBox::information(this, "提示", "手机号码功能正在开发中...");
        } else if (objectName == "label_modifyPassword") {
            // 打开修改密码对话框
            ChangePasswordDialog dlg(this);
            dlg.exec();
        } else if (objectName == "label_feedback") {
            // 打开意见反馈对话框
            FeedbackDialog dlg(this);
            dlg.exec();
        } else if (objectName == "label_userAgreement") {
            //openServerHelpPage(QUrl("https://class.hyzyt.cn/static/agreement/user_agreement.html"), QSize(1920, 1080));
            QDesktopServices::openUrl(QUrl("https://class.hyzyt.cn/static/agreement/user_agreement.html"));

        } else if (objectName == "label_childAgreement") {
            QDesktopServices::openUrl(QUrl("https://class.hyzyt.cn/static/agreement/privacy_children.html"));

        } else if (objectName == "label_privacyPolicy") {
            QDesktopServices::openUrl(QUrl("https://class.hyzyt.cn/static/agreement/privacy.html"));

        } else if (objectName == "label_arrow") {
            QDesktopServices::openUrl(QUrl("https://class.hyzyt.cn/static/agreement/user_agreement.html"));

        } else if (objectName == "label_arrow_2") {
            QDesktopServices::openUrl(QUrl("https://class.hyzyt.cn/static/agreement/privacy_children.html"));

        } else if (objectName == "label_arrow_3") {
            QDesktopServices::openUrl(QUrl("https://class.hyzyt.cn/static/agreement/privacy.html"));
        }
    }
}

void MainWindow::onLogoutButtonClicked()
{
    QMessageBox::information(this, "提示", "退出登录功能正在开发中...");
}

void MainWindow::onScheduleDataReceived(QNetworkReply* reply)
{
    // 检查请求是否成功
    if (reply->error() == QNetworkReply::NoError) {
        // 读取响应数据
        QByteArray responseData = reply->readAll();

        // 清空现有数据
        m_pCourseModel->removeRows(0, m_pCourseModel->rowCount());

        // 解析JSON数据
        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
        if (!jsonDoc.isNull() && jsonDoc.isObject()) {
            QJsonObject jsonObj = jsonDoc.object();

            // 检查是否有数据字段
            if (jsonObj.contains("data") && jsonObj["data"].isArray()) {
                QJsonArray coursesArray = jsonObj["data"].toArray();

                // 设置表格行数
                m_pCourseModel->setRowCount(coursesArray.size());

                // 遍历课程数据并更新UI
                for (int i = 0; i < coursesArray.size(); ++i) {
                    QJsonObject courseObj = coursesArray[i].toObject();

                    // 提取课程信息（根据实际API结构调整字段名）
                    QString courseName = courseObj["class_name"].toString();
                    QString courseTime = courseObj["start_time"].toString();
                    QString duration = courseObj["duration"].toString();
                    QString status = courseObj["status"].toString();

                    // 填充表格数据
                    m_pCourseModel->setItem(i, 0, new QStandardItem(courseName));
                    m_pCourseModel->setItem(i, 1, new QStandardItem(courseTime));
                    m_pCourseModel->setItem(i, 2, new QStandardItem(duration));
                    m_pCourseModel->setItem(i, 3, new QStandardItem(status));

                    // 添加操作按钮
                    QPushButton* enterButton = new QPushButton(QStringLiteral("进入教室"));
                    enterButton->setStyleSheet("QPushButton { background-color: #4d80f0; color: white; border: none; border-radius: 4px; padding: 5px 10px; }"
                                               "QPushButton:hover { background-color: #7199f3; }"
                                               "QPushButton:pressed { background-color: #337ecc; }");
                    //ui->tableView->setIndexWidget(m_pCourseModel->index(i, 4), enterButton);
                }

                // 更新课程统计信息
                QString infoText = QStringLiteral("%1年%2月共%3节课").arg(m_selectedDate.year()).arg(m_selectedDate.month()).arg(coursesArray.size());
                ui->label_4->setText(infoText);
            }
        }
    } else {
        // 处理错误
        qDebug() << "Network error:" << reply->errorString();
        QMessageBox::warning(this, QStringLiteral("网络错误"), QStringLiteral("获取课程数据失败: ") + reply->errorString());
    }

    // 清理reply对象
    reply->deleteLater();
}

void MainWindow::onCalendarSelectionChanged()
{
    m_selectedDate = ui->calendarWidget->selectedDate();
    //loadScheduleData(m_selectedDate);
}


#include <QBuffer>

#if 0
// 获取课表数据
void MainWindow::loadCourseCards()
{
    qDebug() << "enter loadCourseCards!";

    QNetworkRequest req(QUrl("http://cs8.hyzyt.cn/vc/class/list"));

    /* 必须手动指定 multipart boundary，否则后端无法解析 */
    QHttpMultiPart *multi = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    auto add = [multi](const char *k, const QString &v){
        QHttpPart p;
        p.setHeader(QNetworkRequest::ContentDispositionHeader,
                    QString("form-data; name=\"%1\"").arg(k));
        p.setBody(v.toUtf8());
        multi->append(p);
    };

    // token从登陆获取
    QString token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyMCwidXNlcl9pbmZvIjp7ImlkIjoyMCwiYXJlYWNvZGUiOiIrODYiLCJ1c2VybmFtZSI6IjE4NioqKio1MTIyIiwibmlja25hbWUiOiJcdTZjODlcdTllZDhcdTc2ODRcdTk2ZWFcdTc4YTdcdTU1YjUiLCJoZWFkaW1nIjoiaHR0cHM6Ly9pbWcueHllZHUubmV0L3N0b3JhZ2UvcW1tL2ltYWdlcy9oZWFkLzIwMjQxMjExLzEwMDIzNC8vMjAyNDEyMTEvYzljNmEyMmVmYjM0OGIwMjI4MWIyNTY2YzViNWQwMDUucG5nIiwic3RhdHVzIjoxLCJjcmVhdGVfdGltZSI6MTc0MDExOTYyNiwibGFzdF9sb2dpbl90aW1lIjoxNzU2MTI3MTQzLCJlcXVpcG1lbnRfaWQiOiIwOTYyZmVhNzlhZWEzZDliNTcwNjQ1OTZkNDQ5YTA4ZCIsImlkZW50aXR5Ijoic3R1ZGVudCJ9LCJleHAiOjE3NTg3MTkxOTh9.4mZvSEPbYvtDPNNRExuntrR6JO8ZNNEBJh75M_0-Y-0";

    add("token",      token);
    add("app_id",     "2");
    // add("page",       "1");
    // add("per_page",   "10");
    //add("type",       "0");
    //add("state",      "-1");
    add("start_time", "1756171500");
    add("end_time",   "1756344300");
    add("lang",       "zh-cn");
    add("order",      "asc");

    QNetworkReply *reply = m_net.post(req, multi);
    multi->setParent(reply);          // Released along with the reply

    connect(reply, &QNetworkReply::finished, this, [this, reply]{
        qDebug() << "HTTP status:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        qDebug() << "payload:" << reply->readAll();
        reply->deleteLater();
    });
}
#endif

#if 0  // 构造body
void MainWindow::loadCourseCards()
{
    qDebug() << "enter loadCourseCards!";

    QNetworkRequest req(QUrl("http://cs8.hyzyt.cn/vc/class/list"));

    // 1. 生成随机 boundary
    QString boundary = "boundary_." + QUuid::createUuid().toString(QUuid::WithoutBraces);

    // 2. 手动拼 multipart/form-data body
    QByteArray body;
    auto add = [&body, &boundary](const char *name, const QString &value)
    {
        body.append("--" + boundary.toLatin1() + "\r\n");
        body.append(QString("Content-Disposition: form-data; name=\"%1\"\r\n\r\n").arg(name).toUtf8());
        body.append(value.toUtf8() + "\r\n");
    };

    QString token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyMCwidXNlcl9pbmZvIjp7ImlkIjoyMCwiYXJlYWNvZGUiOiIrODYiLCJ1c2VybmFtZSI6IjE4NioqKio1MTIyIiwibmlja25hbWUiOiJcdTZjODlcdTllZDhcdTc2ODRcdTk2ZWFcdTc4YTdcdTU1YjUiLCJoZWFkaW1nIjoiaHR0cHM6Ly9pbWcueHllZHUubmV0L3N0b3JhZ2UvcW1tL2ltYWdlcy9oZWFkLzIwMjQxMjExLzEwMDIzNC8vMjAyNDEyMTEvYzljNmEyMmVmYjM0OGIwMjI4MWIyNTY2YzViNWQwMDUucG5nIiwic3RhdHVzIjoxLCJjcmVhdGVfdGltZSI6MTc0MDExOTYyNiwibGFzdF9sb2dpbl90aW1lIjoxNzU2MTI3MTQzLCJlcXVpcG1lbnRfaWQiOiIwOTYyZmVhNzlhZWEzZDliNTcwNjQ1OTZkNDQ5YTA4ZCIsImlkZW50aXR5Ijoic3R1ZGVudCJ9LCJleHAiOjE3NTg3MTkxOTh9.4mZvSEPbYvtDPNNRExuntrR6JO8ZNNEBJh75M_0-Y-0";

    add("token",      token);
    add("app_id",     "2");
    add("start_time", "1756171500");
    add("end_time",   "1756344300");
    add("lang",       "zh-cn");
    add("order",      "asc");

    body.append("--" + boundary.toLatin1() + "--\r\n");   // 结束标志

    // 3. 打印完整请求报文
    qDebug().noquote() << "------ REQUEST ------";
    qDebug().noquote() << "POST" << req.url().toString() << "HTTP/1.1";
    qDebug().noquote() << "Content-Type: multipart/form-data; boundary=" + boundary.toLatin1();
    qDebug().noquote() << "Content-Length:" << body.size();
    qDebug().noquote() << "";
    qDebug().noquote() << body;
    qDebug().noquote() << "---------------------";

    // 4. 发送（不再使用 QHttpMultiPart）
    req.setHeader(QNetworkRequest::ContentTypeHeader,
                  "multipart/form-data; boundary=" + boundary.toLatin1());
    req.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(body.size()));

    QNetworkReply *reply = m_net.post(req, body);

    connect(reply, &QNetworkReply::finished, this, [this, reply]{
        qDebug() << "HTTP status:" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        qDebug() << "payload:" << reply->readAll();
        reply->deleteLater();
    });
}
#endif

#if 0
void MainWindow::loadCourseCards()
{
    qDebug() << "enter loadCourseCards!";
    QNetworkRequest req(QUrl("http://cs8.hyzyt.cn/vc/class/list"));

    QHttpMultiPart *multi = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    // 改造这个 lambda：不仅添加 part，还打印 key-value
    auto add = [multi](const char *k, const QString &v){
        qDebug() << "[请求参数] key =" << k << ", value =" << v;  // 打印每个参数

        QHttpPart p;
        p.setHeader(QNetworkRequest::ContentDispositionHeader,
                    QString("form-data; name=\"%1\"").arg(k));

        // p.setHeader(QNetworkRequest::ContentDispositionHeader,
        //              QVariant("application/json"));

        p.setBody(v.toUtf8());
        multi->append(p);
    };

    // token从登陆获取
    QString token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyMCwidXNlcl9pbmZvIjp7ImlkIjoyMCwiYXJlYWNvZGUiOiIrODYiLCJ1c2VybmFtZSI6IjE4NioqKio1MTIyIiwibmlja25hbWUiOiJcdTZjODlcdTllZDhcdTc2ODRcdTk2ZWFcdTc4YTdcdTU1YjUiLCJoZWFkaW1nIjoiaHR0cHM6Ly9pbWcueHllZHUubmV0L3N0b3JhZ2UvcW1tL2ltYWdlcy9oZWFkLzIwMjQxMjExLzEwMDIzNC8vMjAyNDEyMTEvYzljNmEyMmVmYjM0OGIwMjI4MWIyNTY2YzViNWQwMDUucG5nIiwic3RhdHVzIjoxLCJjcmVhdGVfdGltZSI6MTc0MDExOTYyNiwibGFzdF9sb2dpbl90aW1lIjoxNzU2MTI3MTQzLCJlcXVpcG1lbnRfaWQiOiIwOTYyZmVhNzlhZWEzZDliNTcwNjQ1OTZkNDQ5YTA4ZCIsImlkZW50aXR5Ijoic3R1ZGVudCJ9LCJleHAiOjE3NTg3MTkxOTh9.4mZvSEPbYvtDPNNRExuntrR6JO8ZNNEBJh75M_0-Y-0";

    bool identy = true;
    add("token",      token);
    add("app_id",     "2");
    add("start_time", "1756171500");
    add("end_time",   "1756344300");
    add("lang",       "zh-cn");
    add("order",      "asc");
    add("isTeacher",   QVariant(identy).toString());

    qDebug() << "当前请求使用的是 multipart/form-data 格式";

    QNetworkReply *reply = m_net.post(req, multi);
    multi->setParent(reply);  // Released along with the reply

    connect(reply, &QNetworkReply::finished, this, [this, reply]{
        int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        qDebug() << "HTTP status:" << statusCode;

        QByteArray rawData = reply->readAll();
        QJsonParseError parseError;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData, &parseError);

        if (parseError.error == QJsonParseError::NoError && !jsonDoc.isNull()) {
            QJsonObject obj = jsonDoc.object();
            qDebug() << "code:" << obj["code"].toInt();
            qDebug() << "message:" << obj["message"].toString();
            qDebug() << "data:" << obj["data"].toObject();
        } else {
            qDebug() << "JSON 解析失败:" << parseError.errorString();
            qDebug() << "原始返回数据:" << rawData;
        }

        reply->deleteLater();
    });
}


/* ========== Parse JSON and populate cards ========== */
void MainWindow::onCourseReply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply) return;

    qDebug() << "reply error:" << reply->error()
             << "http code:"   << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()
             << "payload size:"<< reply->size();

    if (reply->error() == QNetworkReply::NoError) {
        QJsonDocument doc = QJsonDocument::fromJson(reply->readAll());
        QJsonArray arr = doc["data"]["list"].toArray();
        for (const QJsonValue &v : arr) {
            QJsonObject o = v.toObject();
            QString title = o["class_name"].toString();
            QString time  = QString("%1 ~ %2")
                               .arg(QDateTime::fromSecsSinceEpoch(o["class_start_time"].toInt())
                                        .toString("MM-dd hh:mm"))
                               .arg(QDateTime::fromSecsSinceEpoch(o["class_end_time"].toInt())
                                        .toString("hh:mm"));
            QString stu   = o["student_names"].toString();
            QString cover = o["payback_cover"].toString();
            int status    = o["status"].toInt();

            QListWidgetItem *item = new QListWidgetItem(ui->listWidget);
            item->setSizeHint(QSize(0, 120));
            ui->listWidget->setItemWidget(item, new CourseCard_(title, time, stu, cover, status, this));
        }
    } else {
        qWarning() << "HTTP error" << reply->error()
        << reply->errorString()
        << reply->readAll();   // Server returned error page
    }
    reply->deleteLater();
}
#endif


// 课程列表获取 https://docs.apipost.net/docs/detail/40adfb9b8ce0000?target_id=3d831847dcb2a
void MainWindow::SendPostRequst(const QString& strhead,QByteArray arr)
{
    QString url = "http://cs8.hyzyt.cn" + strhead;
    QNetworkRequest _quest;
    _quest.setUrl((QUrl(url)));
    qDebug()<<url;
    _quest.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));

    if (!mNet_) {
        mNet_ = new QNetworkAccessManager(this);
    }

    mReply_ = mNet_->post(_quest,arr);
    connect(mReply_,&QNetworkReply::finished,this,[=]{
        ReplyFinshed();
    });
}

void MainWindow::ReplyFinshed()
{
    if (mReply_->error() == QNetworkReply::NoError)
    {
        // 处理返回的数据
        QByteArray _data = mReply_->readAll();//读出数据
        QJsonDocument doc = QJsonDocument::fromJson(_data);
        if (doc.isNull())
        {
            qDebug() << "Failed to parse JSON.";
            mReply_->deleteLater();
            return;
        }
        qDebug()<<_data;
        
        // 清空listWidget中的现有项目
        ui->listWidget->clear();
        
        // 解析JSON数据
        QJsonObject jsonObj = doc.object();
        if (jsonObj.contains("data") && jsonObj["data"].isObject()) {
            QJsonObject dataObj = jsonObj["data"].toObject();
            if (dataObj.contains("list") && dataObj["list"].isArray()) {
                QJsonArray courseArray = dataObj["list"].toArray();
                
                // 遍历课程列表，为每个课程创建卡片
                for (const QJsonValue &value : courseArray) {
                    QJsonObject courseObj = value.toObject();
                    
                    // 提取所需字段
                    QString class_name = courseObj["class_name"].toString();
                    QString grade = courseObj["grade"].toString();
                    QString student_names = courseObj["student_names"].toString();
                    qint64 class_start_time = courseObj["class_start_time"].toVariant().toLongLong();
                    qint64 class_end_time = courseObj["class_end_time"].toVariant().toLongLong();
                    int status = courseObj["status"].toInt();
                    
                    // 格式化时间显示
                    QString timeRange = QString("%1 ~ %2")
                        .arg(QDateTime::fromSecsSinceEpoch(class_start_time).toString("MM-dd hh:mm"))
                        .arg(QDateTime::fromSecsSinceEpoch(class_end_time).toString("hh:mm"));
                    
                    // 组合学生姓名和年级信息
                    QString studentAndGrade = QString("%1 %2").arg(student_names).arg(grade);
                    
                    // 创建列表项和课程卡片
                    QListWidgetItem *item = new QListWidgetItem(ui->listWidget);
                    item->setSizeHint(QSize(0, 120));
                    ui->listWidget->setItemWidget(item, new CourseCard_(class_name, timeRange, studentAndGrade, "", status, this));
                }
            }
        }
    }
    else
    {
        // 处理错误
        qDebug()<<"error ==> "<<mReply_->error();
    }
    mReply_->deleteLater();
}

void MainWindow::getCourseList()
{
    QJsonObject rawJson;
    rawJson["token"] = CUserLogin::getToken();
    rawJson["app_id"] = "2";
    rawJson["start_time"] = "1753977599";
    rawJson["end_time"] = "1756656000";
    rawJson["lang"] = "zh-cn";
    rawJson["order"] = "asc";
    rawJson["isTeacher"] = true;

    //设置为json格式数据
    QByteArray byte_array = QJsonDocument(rawJson).toJson();
    SendPostRequst(GET_CLASS_LIST_TEACHER,byte_array);
    // if(ret)
    // {
    //     qDebug() << "get course list failed!!!";
    // }
}
